<?php


namespace App\Helpers;


use App\Models\ActionLog;
use App\Models\Divide\City;
use App\Models\Divide\CitySplitRatio;
use App\Models\Divide\Department;
use App\Models\Divide\DepartmentSplitRatio;
use App\Models\Divide\DepartmentSplitRatioLog;
use App\Models\Divide\PdPdLog;
use App\Models\Divide\PdUserRelationship;
use App\Models\Divide\PersonSplitRatio;
use App\Models\Mch\RegisterCode;
use Carbon\Carbon;

trait DepartmentCommisionTrait
{
    // 合伙制处理
    protected function partnerShip($order,$money){
        $department = Department::query()
            ->select('department_id','ratio')
            ->where('category_id',$order->account_mode)
            ->get();
        foreach ($department as $item){
            $departemnt_money = bcmul($money, $item->ratio, 2);
            $users = $this->getDepartemntUser($item->category_id,$item->department_id);
            foreach ($users as $user){
                $user_money = bcmul($departemnt_money, $user->ratio, 2);
                $this->departmentDivideLog($user,$order,$user_money,$money);
                // 设置用户待到账金额
                $this->setUserWaittionMoney($user,$money,$order,$item->department_id);
            }
        }
    }
    /**
     * 获取部门员工
     * @param $category_id
     * @param $department_id
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    protected function getDepartemntUser($category_id,$department_id){
        return DepartmentSplitRatio::query()
            ->where('category_id',$category_id)
            ->where('department_id',$department_id)
            ->get();
    }

    /**
     * 部门分佣记录
     * @param $user
     * @param $order
     * @param $money
     * @return void
     */
    protected function departmentDivideLog($user,$order,$money,$department_money){
        $department_log = [
            'category_id'=>$user->category_id,
            'department_id'=>$user->department_id,
            'ratio'=>$user->ratio,
            'user_id'=>$user->user_id,
            'name'=>$user->name,
            'avatar'=>$user->avatar,
            'money'=>$money,
            'order_id'=>$order->order_id,
            'department_money'=>$department_money
        ];
        DepartmentSplitRatioLog::query()->create($department_log);
    }


}

